package com.niit.repository;

import com.niit.entity.Message;
import com.niit.entity.MessageObject;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Collection;
import java.util.List;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

public interface MessageRepository extends JpaRepository<Message, Integer> {
    // 根据发送者和接收者的id查询消息
//    @Query("SELECT m FROM Message m WHERE " +
//            "(m.messageObject.sender.id = :senderId AND m.messageObject.receiver.id = :receiverId) OR " +
//            "(m.messageObject.sender.id = :receiverId AND m.messageObject.receiver.id = :senderId) " +
//            "ORDER BY m.sendTime ASC")
//    List<Message> findById(
//            @Param("senderId") Integer senderId,
//            @Param("receiverId") Integer receiverId,
//            @Param("senderId") Integer senderId2,
//            @Param("receiverId") Integer receiverId2);
//
//    @Query("SELECT m FROM Message m WHERE " +
//            "(m.messageObject.sender.id = :senderId) " + "ORDER BY m.sendTime ASC")
//    List<Message> findBySenderId(Integer senderId);

    List<Message> findAllByMessageObject_IdInOrderBySendTimeAsc(Collection<Integer> messageObject_id);

    @Query("""
        SELECT m
        FROM Message m
        WHERE m.id IN (
            SELECT MAX(m2.id)
            FROM Message m2
            WHERE (m2.messageObject.sender.id = :currentUserId OR m2.messageObject.receiver.id = :currentUserId)
            GROUP BY 
                CASE 
                    WHEN m2.messageObject.sender.id = :currentUserId THEN m2.messageObject.receiver.id
                    ELSE m2.messageObject.sender.id
                END
        )
        ORDER BY m.sendTime DESC
    """)
    List<Message> findLastMessagesPerPeer(@Param("currentUserId") Integer currentUserId);
}
